import React, { useRef, forwardRef, useImperativeHandle, useState,Memo } from "react"

// forwardRef和useImperativeHandle结合使用
// useImperativeHandle还可以控制暴露粒度 

const Child = forwardRef((props, ref) => {
   
    const [count, setCount] = useState(0)
    const add = (number) => {
        setCount((pre) => pre += number)
    }
     // useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值。主要是自定义
    // 给父组件暴露setCount回调函数
    // 1、useImperativeHandle(ref, () => ({ setCount })) 改成以下 不给setcount出去
    useImperativeHandle(ref, () => ({reset:()=> setCount(0) }))

    return <>
        <button onClick={()=>add(1)}>+1</button>
        <button onClick={()=>add(-1)}>-1</button>
        <h1>{count}</h1>
    </>


})


export const Father = () => {
    const childRef = useRef(null)
    const show = () => {
        console.log(childRef.current,'---childRef.current');
    }

    const reset=()=>{
        childRef.current?.reset()
    }
    return (<>
        <h1>这是父组件</h1>

        <button onClick={show}>show ref</button>
        <button onClick={reset}>重置</button>
        <hr />
        <Child ref={childRef} />
    </>)
}